package com.nlscan.qdkit.common.core.util

import android.bluetooth.BluetoothDevice
import android.text.TextUtils
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method


/**
 * <pre>
 *  author: lin.qing
 *  time  : 2023/3/30
 *  desc  :
 * </pre>
 */
object BluetoothUtils {

    /*
     * 备注
     * -- @hide 方法需要用放射来调用
     */

    /**
     * 获取重命名后的名称
     * -- 2023-04-21 若未设置别名返回设备名
     * @param device
     * @return
     */
    fun getAliasName(device: BluetoothDevice?): String? {
        if (device == null) {
            return ""
        }

        // TODO: 适配Android12权限

        var deviceAlias: String? = ""
//            device.name
        try {
            deviceAlias = device.name

            val method: Method? = device.javaClass.getMethod("getAlias")
            if (method != null) {
                //【报错】java.lang.NullPointerException: null cannot be cast to non-null type kotlin.String
                //导致添加设备失败，页面一直显示为连接中
                deviceAlias = method.invoke(device) as String?
            }
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: NullPointerException) {
            e.printStackTrace()
        } catch (e: Exception) {
            // TODO: 增加LogUtil
            e.printStackTrace()
        }

        try {
            //[bugFix]修复未设置别名导致返回值为空
            if (TextUtils.isEmpty(deviceAlias)) {
                deviceAlias = device.name
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return deviceAlias
    }

    /**
     * todo 确认是否有返回值
     * 对设备进行重命名
     * @param device
     * @param newName
     */
    fun setAliasName(device: BluetoothDevice?, newName: String?) {
        if (device == null || newName == null || newName.isEmpty()) {
            return
        }
        try {
            val method: Method? = device.javaClass.getMethod("setAlias", String::class.java)
            if (method != null) {
                method.invoke(device, newName)
            }
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
    }

}